package com.example.wiki3.activaty;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;


import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import com.example.wiki3.Dao.DatabaseHelper;
import com.example.wiki3.R;
import com.example.wiki3.Retrofit.ApiService;
import com.example.wiki3.Retrofit.RetrofitClient;


import com.example.wiki3.entity.BookContent;
import com.example.wiki3.entity.BookItemListResponse;


import com.example.wiki3.frameLayout.ContentFragment;
import com.example.wiki3.tree.Dept;
import com.example.wiki3.tree.Node;
import com.example.wiki3.tree.NodeHelper;
import com.example.wiki3.tree.NodeTreeAdapter;


import java.util.ArrayList;

import java.util.LinkedList;
import java.util.List;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainActivity extends AppCompatActivity {

    private String TAG = "11111";

    private DrawerLayout drawerLayout;
    private ListView treeListView;
    private NodeTreeAdapter mAdapter;
    private LinkedList<Node> mLinkedList = new LinkedList<>();
    private FrameLayout ContentFrameLayout;
    private Context mContext;
    //db
    private DatabaseHelper dbHelper;
    private SQLiteDatabase db;
    private ContentFragment contentFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this; // 初始化mContext

        //初始化
        init();
        //树形列表图形设置适配器
        mAdapter = new NodeTreeAdapter(this, treeListView, mLinkedList);
        treeListView.setAdapter(mAdapter);
        // 设置ListView的点击监听器
        treeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this);
                // 1.获取选中的节点
                Node selectedNode = (Node) parent.getItemAtPosition(position);
                // 2.展开或折叠节点
                mAdapter.expandOrCollapse(position);
                // 3获取内容到数据库
                getbookitemContent(selectedNode.get_id(), dbHelper, new OnDataLoadListener() {
                    @Override
                    public void onDataLoaded(String content) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 根据加载的数据更新UI
                                contentFragment.updateContent( selectedNode.get_label(),content);
                                Log.d(TAG, "onDataLoaded: success");
                            }
                        });

                        // 4更新内容视图
//                        updateContentView(selectedNode); // 添加这一行来更新内容视图
                        Log.d(TAG, "onItemClick: 设置ListView的点击监听器" + position + id);
                    }

                    @Override
                    public void onError(String e) {
                        // 显示错误信息或采取其他错误处理措施
                        Log.d(TAG, "onError: " + e);
                    }
                });
                //


            }
        });


        // 动态添加ContentFragment（如果尚未在XML布局中静态定义）

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        contentFragment = (ContentFragment) fragmentManager.findFragmentById(R.id.setcontent);

        if (contentFragment == null) {
            contentFragment = new ContentFragment();
            transaction.replace(R.id.setcontent, contentFragment);
            transaction.commit();
        }


        initData();

    }


    /**
     * 更新内容视图
     *
     * @param node
     */
    private void updateContentView(Node node) {

        String content = "";
        String name = "";
        // 1. 优先尝试从数据库读取内容
        DatabaseHelper dbHelper = null;
        try {
            dbHelper = new DatabaseHelper(MainActivity.this);
            db = dbHelper.getReadableDatabase();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String[] columns = {"name", "content"};
        String selection = "id = ?";
        String[] selectionArgs = {String.valueOf(node.get_id())};
        // 执行查询
        Cursor cursor = db.query("book_content", columns, selection, selectionArgs, null, null, null);
        Log.d(TAG, "updateContentView: 数据库开始1");

        if (cursor != null && cursor.moveToFirst()) { // 检查Cursor是否有效且有数据
            name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
            Log.d(TAG, "updateContentView: 数据库开始2");
            if (name.equals(node.get_label())) {
                Log.d(TAG, "updateContentView: 数据库开始3");
                contentFragment.updateContent(name, content);
            }
        } else {
            Log.d(TAG, "updateContentView: No data found in the database for the given ID.");
        }

        db.close();
        // 2. 如果数据库中没有内容，则使用节点提供的消息或发起网络请求获取
        if (content == null) {
            getbookitemContent(node.get_id(), dbHelper, new OnDataLoadListener() {
                @Override
                public void onDataLoaded(String content) {
                    Log.d(TAG, "onDataLoaded: success");
                }

                @Override
                public void onError(String e) {

                }
            });
        }
    }


    private void initData() {
        List<Node> data = new ArrayList<>();
//        get请求获取电子书的分类

        getbookitemList(data);
    }

    private void init() {
        ContentFrameLayout = findViewById(R.id.setcontent);
        //我的左侧树形列表
        treeListView = (ListView) findViewById(R.id.id_tree);
        setSupportActionBar(findViewById(R.id.toolbar));
        //可以滑动菜单
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        ActionBar actionBar = getSupportActionBar();
        //设置导航按钮
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.menu);







        }

    }

    //导航栏的设置
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    //导航栏的设置
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.add) {

            Toast.makeText(this, "点击了新增按钮", Toast.LENGTH_SHORT).show();
        } else if (itemId == R.id.set) {
            Toast.makeText(this, "点击了设置按钮", Toast.LENGTH_SHORT).show();
        } else if (itemId == android.R.id.home) {
            drawerLayout.openDrawer(GravityCompat.START);

        }

        return true;
    }


    //请求书的方法
    private void getbookitemList(List<Node> data) {

        ApiService apiService = RetrofitClient.getApiService();
        apiService.getoneBookList().enqueue(new Callback<BookItemListResponse>() {
            @Override
            public void onResponse(Call<BookItemListResponse> call, Response<BookItemListResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    BookItemListResponse.BookItem[] bookItemList = response.body().getContent();

                    //写入数据库
                    DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this); // 使用MainActivity.this作为上下文
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();

                    for (BookItemListResponse.BookItem item : bookItemList) {
                        data.add(new Dept(item.getId(), item.getParent(), item.getName()));

                        values.put("id", item.getId());
                        values.put("parent", item.getParent());
                        values.put("name", item.getName());
                        values.put("sort", item.getSort());
                        values.put("viewCount", item.getViewCount());
                        values.put("voteCount", item.getVoteCount());
                        values.put("ebookId", item.getEbookId());
                        db.insert("book_content", null, values);

                    }
                    db.close();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLinkedList.clear(); // 先清空原有数据，防止重复添加

                            // 更新数据源
                            mLinkedList.addAll(NodeHelper.sortNodes(data));
                            // 重要：通知Adapter数据已变化
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<BookItemListResponse> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
            }
        });

    }


    /**
     * 发起请求,把内容写到数据库
     *
     * @param id
     * @param dbHelper
     */
    private void getbookitemContent(long id, final DatabaseHelper dbHelper, final OnDataLoadListener listener) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                ApiService apiService = RetrofitClient.getApiService();
                apiService.getoneBookContent(id).enqueue(new Callback<BookContent>() {
                    @Override
                    public void onResponse(Call<BookContent> call, Response<BookContent> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            String content = response.body().getContent();
                            // 更新数据库

                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            Log.d(TAG, " 更新数据库onResponse: " + content);
                            values.put("content", content);
                            // 这里需要根据bookId更新对应的记录，而不是插入新记录
                            String whereClause = "id = ?";
                            String[] whereArgs = {String.valueOf(id)};
                            db.update("book_content", values, whereClause, whereArgs);
                            db.close();

                            // 数据获取成功，通过回调通知UI线程更新
                            listener.onDataLoaded(content);
                        } else {
                            // 如果响应不成功，也应视为错误
                            listener.onError("网络请求不成功");
                        }


                    }

                    @Override
                    public void onFailure(Call<BookContent> call, Throwable t) {
                        Log.e(TAG, "获取内容失败: " + t.getMessage());
                    }


                });


            }
        }).start();


    }


}